<?php

$db = new SimpleXMLElement(file_get_contents("database.xml"));

/****** write *******/

if(!$_POST['edit_body'] == "") {
  // save link info
  $split = split("}",$_POST['edit_body']);
  for($i=0; $i<count($split)-1; $i++) {
    $segment = $split[$i];
    $split2 = split("{",$segment);
    $final .= $split2[0];
    $linktarget = $split2[1];
    $linkbase = $_GET['show'];
    foreach($db->links->link as $link) {
      $linkalreadyexists = false;
      if($link['from'] == $linkbase) {
        $linkalreadyexists = true;
      }
      if(!$linkalreadyexists) {
        //$newlink = $db->links->addChild("link");
        //$newlink['from'] = $linkbase;
        //$newlink['to'] = $linktarget;
      }
    }
  }
  // write page edit
  foreach($db->pages->page as $editpage) {
    if($editpage['title'] == $_GET['show']) {
      $exists = true;
      $editpage['categories'] = $_POST['edit_categories'];
      $revision = $editpage->addChild("revision",$_POST['edit_body']);
      $revision['time'] = time();
      $revision['id'] = count($editpage->revision)-1;
      
      /*
      // insert redirect if you changed the title
      if(!$editpage['title'] == $_POST['edit_title']) {
        $editpage['title'] = $_POST['edit_title'];
        $redirect = $db->pages->addChild("page","_this page is now {".$_POST['edit_title']."}, old chum_");
        $redirect['type'] = "redirect";
      }
      */
    }
  }
  // write new page
  if(!$exists) {
    $editpage = $db->pages->addChild("page");
    $editpage['categories'] = $_POST['edit_categories'];
    $revision = $editpage->addChild("revision",$_POST['edit_body']);
    $revision['time'] = time();
    $revision['id'] = 0;
    $editpage['title'] = $_POST['edit_title'];
  }
}

// write category parent info (broken...)
if(!$_POST['category_parent'] == "") {
  foreach($db->categories->category as $editcategory) {
    if($category['name'] == $_POST['this_category']) {
      foreach ($db->categories->category as $parentcateory) {
        if($parentcategory['name'] == $_POST['edit_category']) {
          $editcategory['parent'] = $parentcategory['name'];
        }
      }
    }
  }
}

/****** read *******/

// get page
$pageexists = false;
foreach($db->pages->page as $currentpage) {
  if(strtolower($currentpage['title']) == strtolower($pagename)) {
    $pageexists = true;
    $page = $currentpage;
  }
}

// get revision if specified
if(!$_GET['revision'] == "" || $_GET['revision'] == "0") {
  $revision = $page->revision[$_GET['revision']+0];
} else {
  $revision = $page->revision[count($page->revision)-1];
}
$revisionid = $revision['id']+0;

/********* save changes *********/
// write changes & close up...
$write = fopen("database.xml","w");
fwrite($write,$db -> asXML());
fclose($write);
?>